package com.cherry.i18n.core;

import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * 可加载不同Jar包消息源配置
 *
 * @author sinbad.cheng
 * @since 2022-01-07
 */
public class ClassPathResourceBundleMessageSource extends ReloadableResourceBundleMessageSource {

    private static final String PROPERTIES_SUFFIX = ".properties";

    private final PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

    @Override
    protected List<String> calculateFilenamesForLocale(String basename, Locale locale) {
        List<String> fileNames = new ArrayList<>();
        List<String> matchFilenames = super.calculateFilenamesForLocale(basename, locale);
        try {
            for (String matchFilename : matchFilenames) {
                Resource[] resources = resolver.getResources("classpath*:" + matchFilename + PROPERTIES_SUFFIX);
                for (Resource resource : resources) {
                    String sourcePath = resource.getURI().toString().replace(PROPERTIES_SUFFIX, "");
                    fileNames.add(sourcePath);
                }
            }
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
        return fileNames;
    }

}